package com.apesay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apesay.exception.ServiceException;
import com.apesay.service.base.ClientService;
import com.apesay.service.work.ProjectService;
import com.apesay.utils.Constant;
import com.apesay.utils.DataUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/project")
public class ProjectController extends RestController{
	@Autowired
	private ProjectService projectService;
	@Autowired
	private ClientService clientService;
	@Resource
	private HttpSession session;
	
	@RequiresAuthentication
	@RequestMapping("/manage")
	public String manage(){
		return "project/manage";
	}
	@RequiresAuthentication
	@RequestMapping("/add")
	@ResponseBody
	public JSONObject add(String projectName, String projectDescription){
		if (!DataUtils.isNotEmpty(projectName)) {
			throw new ServiceException("项目名不能为空");
		}
		JSONObject userObj = (JSONObject) session.getAttribute("currentaccount");//当前登录用户
		String userId = userObj.getString(Constant.OBJECTID);
		JSONObject jsonObject = new JSONObject();
		JSONArray workers = new JSONArray();
		workers.add(userId);
		jsonObject.put("creater",userId);
		jsonObject.put("projectName",projectName);
		jsonObject.put("projectDescription",projectDescription);
		jsonObject.put("workers",workers);
		JSONObject save = projectService.save(jsonObject);
		JSONObject model = new JSONObject();
		JSONObject data = new JSONObject();
		data.put("data",save);
		model.put("succeed", 1);
		model.put("message", data);
		return model;
	}
	@RequiresAuthentication
	@RequestMapping("/edit")
	public String edit(String objectId,Model model){
		model.addAttribute(Constant.OBJECTID, objectId);
		return "project/edit";
	}
	@RequiresAuthentication
	@RequestMapping("/mylist")
	@ResponseBody
	public JSONObject mylist(String objectId){
		JSONObject userObj = (JSONObject) session.getAttribute("currentaccount");//当前登录用户
		JSONArray objects = projectService.listByUserId(userObj.getString(Constant.OBJECTID));
		JSONObject model = new JSONObject();
		JSONObject data = new JSONObject();
		data.put("data",objects);
		model.put("succeed", 1);
		model.put("message", data);
		return model;
	}
	
	
	@Override
	protected String getModel() {
		return Constant.model_project;
	}
}
